package com.zzh.takeoutapp.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zzh.takeoutapp.R;
import com.zzh.takeoutapp.activity.LoginActivity;
import com.zzh.takeoutapp.activity.OrderDetailsActivity;
import com.zzh.takeoutapp.adapter.OnRecyleItemClick;
import com.zzh.takeoutapp.adapter.OrderListAdapter;
import com.zzh.takeoutapp.base.BaseFragment;
import com.zzh.takeoutapp.config.UrlConfig;
import com.zzh.takeoutapp.entity.OrderListBean;
import com.zzh.takeoutapp.event.NetMsgEvent;
import com.zzh.takeoutapp.model.ModelUtil;
import com.zzh.takeoutapp.service.EventbusHelper;
import com.zzh.takeoutapp.service.ServiceUrl;
import com.zzh.takeoutapp.utils.GsonResolve;
import com.zzh.takeoutapp.utils.LoadingUtil;
import com.zzh.takeoutapp.utils.NetWorkUtils;
import com.zzh.takeoutapp.utils.SPUtils;
import com.zzh.takeoutapp.utils.UtilTool;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/7/13.
 */

public class OrderListFragment extends BaseFragment implements View.OnClickListener, OnRefreshListener, OnLoadmoreListener {
    @Bind(R.id.tv_empty_text)
    TextView tv_empty_text;
    @Bind(R.id.tv_login)
    TextView tv_login;
    @Bind(R.id.ll_login)
    LinearLayout ll_login;
    @Bind(R.id.empty_text)
    NestedScrollView mEmptyLayout;//设置没有数据网络的情况
    @Bind(R.id.refreshLayout)
    RefreshLayout mRefreshLayout;
    @Bind(R.id.recyclerView)
    RecyclerView mRecyclerView;
    private OrderListAdapter oneFragmentAdapter;
    private List<OrderListBean> listBeanList;
    private final String ORDER_LIST0 = "OrderListFragment0";
    private final String ORDER_LIST1 = "OrderListFragment1";
    private final String ORDER_LIST2 = "OrderListFragment2";
    private final String ORDER_LIST3 = "OrderListFragment3";
    private final String CHARGE_BACK = "chargeback";//取消订单
    private final String REMIND_SERVICE = "remindService";//催单

    private boolean isLogin;
    private int type;
    protected static final String NEWS_ID = "news_id";
    public static final int ALL = 0;//全部
    public static final int PAY = 1;//支付
    public static final int EVA = 2;//评价
    public static final int REFUND = 3;//退款
    private int CURPAGE = 1;//加载页码
    private LoadingUtil loadingUtil;

    @Override
    protected void onFragmentVisibleChange(boolean isVisible) {
        super.onFragmentVisibleChange(isVisible);
        if (listBeanList == null && isLogin == false) {
            mRefreshLayout.autoRefresh();
        }
    }

    public static OrderListFragment newInstance(int newsId) {
        OrderListFragment fragment = new OrderListFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(NEWS_ID, newsId);
        fragment.type = newsId;
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void getsavedInstanceState(Bundle savedInstanceState) {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container) {
        View view = inflater.inflate(R.layout.fragment_list_order, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void initComponent(View view) {
        loadingUtil = new LoadingUtil(getActivity());
        mRefreshLayout.autoRefresh();
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setOnLoadmoreListener(this);
        mRefreshLayout.setDisableContentWhenRefresh(true);
        mRefreshLayout.setDisableContentWhenLoading(true);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));//很重要，不然不显示就是一个坑
    }

    @Override
    public void setListener() {
    }

    @Override
    public void onAfterInit() {

    }

    @Override
    public void onStart() {
        super.onStart();
        EventbusHelper.register(this);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (oneFragmentAdapter != null)
            oneFragmentAdapter.cancelAllTimers();
        EventbusHelper.unregister(this);
    }

    private void setmRefreshLayout() {
        mRefreshLayout.finishRefresh();
        mRefreshLayout.finishLoadmore();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMsgEvent(NetMsgEvent event) {
        String _msgType = (String) event.getMsgType();
        JSONObject jsonObject = event.getMsgJSONObj();
        switch (_msgType) {
            case ORDER_LIST0:
                if (type == ALL) {
                    setmRefreshLayout();
                    getData(jsonObject);
                }
                break;
            case ORDER_LIST1:
                if (type == PAY) {
                    setmRefreshLayout();
                    getData(jsonObject);
                }
                break;
            case ORDER_LIST2:
                if (type == EVA) {
                    setmRefreshLayout();
                    getData(jsonObject);
                }
                break;
            case ORDER_LIST3:
                if (type == REFUND) {
                    setmRefreshLayout();
                    getData(jsonObject);
                }
                break;
            case "TV_CANCEL_REFUND"://取消订单
                loadingUtil.startShowLoading();
                ServiceUrl.ChargeBackService(getActivity(), event.getErrorString(), CHARGE_BACK);
                break;
            case CHARGE_BACK://取消订单
                loadingUtil.stopShowLoading();
                if (jsonObject.optString("error").equals("0")) {
                    mRefreshLayout.autoRefresh();
                }
                break;
            case "LL_CUI"://催单
                loadingUtil.startShowLoading();
                ServiceUrl.remindService(getActivity(), event.getErrorString(), REMIND_SERVICE);
                break;
            case REMIND_SERVICE://催单
                loadingUtil.stopShowLoading();
                if (jsonObject.optString("error").equals("0")) {
                    UtilTool.toast(getActivity(),"催单成功");
                }
                break;
        }
    }

    private void getData(JSONObject jsonObject) {
        if (jsonObject != null) {
            if (jsonObject.optString("error").equals("0")) {
                mEmptyLayout.setVisibility(View.GONE);
                mRecyclerView.setVisibility(View.VISIBLE);
                isLogin = false;
                JSONObject object = jsonObject.optJSONObject("data");
                JSONArray jsonArray = object.optJSONArray("items");
                listBeanList = ModelUtil.orderList(jsonArray);
                initData();
            } else if (jsonObject.optString("error").equals("101")) {
                mEmptyLayout.setVisibility(View.VISIBLE);
                ll_login.setVisibility(View.VISIBLE);
                mRecyclerView.setVisibility(View.GONE);
                isLogin = true;
            } else {
                mEmptyLayout.setVisibility(View.VISIBLE);
                ll_login.setVisibility(View.GONE);
                isLogin = false;
                mRecyclerView.setVisibility(View.GONE);
            }
        }
    }

    private void initData() {
        if (CURPAGE == 1) {
            if (listBeanList.size() == 0) {
                mEmptyLayout.setVisibility(View.VISIBLE);
                ll_login.setVisibility(View.GONE);
                mRecyclerView.setVisibility(View.GONE);
            }
            if (oneFragmentAdapter != null) {
                mRefreshLayout.setLoadmoreFinished(false);
            }
            oneFragmentAdapter = new OrderListAdapter(listBeanList, getActivity());
            mRecyclerView.setAdapter(oneFragmentAdapter);
            oneFragmentAdapter.notifyDataSetChanged();
            oneFragmentAdapter.addOnRecyleItemClick(new OnRecyleItemClick() {
                @Override
                public void onItemClick(View v, Object o, int position) {
                    Intent intent = new Intent(getActivity(), OrderDetailsActivity.class);
                    intent.putExtra("order_id", oneFragmentAdapter.getItem(position).getOrder_id());
                    start_Activity(intent);
                }
            });
        } else {
            if (oneFragmentAdapter != null) {
                oneFragmentAdapter.insert(listBeanList, oneFragmentAdapter.getItemCount());
                oneFragmentAdapter.notifyDataSetChanged();
            }
        }
        if (listBeanList == null || listBeanList.size() < 10) {
            mRefreshLayout.setLoadmoreFinished(false);
        } else {
            CURPAGE++;
        }
    }

    @OnClick({R.id.tv_login})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_login:
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                intent.setType("OrderListFragment");
                start_Activity(intent);
                break;
        }
    }

    private void sendService() {
        switch (type) {
            case ALL:
                ServiceUrl.OrderIndexService(getActivity(), CURPAGE, "", ORDER_LIST0);//订单的接口
                break;
            case PAY:
                ServiceUrl.OrderIndexService(getActivity(), CURPAGE, "0", ORDER_LIST1);//订单的接口
                break;
            case EVA:
                ServiceUrl.OrderIndexService(getActivity(), CURPAGE, "1", ORDER_LIST2);//订单的接口
                break;
            case REFUND:
                ServiceUrl.OrderIndexService(getActivity(), CURPAGE, "-1", ORDER_LIST3);//订单的接口
                break;
        }
    }


    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        CURPAGE = 1;
        if (NetWorkUtils.notNetWork(getActivity()) == false) {//没有网络
            mEmptyLayout.setVisibility(View.VISIBLE);
            mRecyclerView.setVisibility(View.GONE);
            refreshlayout.finishRefresh();
        } else {
            if (listBeanList != null)
                listBeanList.clear();
            sendService();
        }
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        sendService();
    }
}
